import random
from celery_tasks.sms.tasks import send_sms_code
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from redis import Redis

from libs.captcha.captcha import captcha
from utils.smsutils import SmsUtil


class ImageCodeView(View):

    def get(self, request, uuid):
        # 1接收前段验证码

        # 2生成验证码
        text , image = captcha.generate_captcha()
        # 3用uuid为key 验证码为value存到redisa
        redis = get_redis_connection('code')
        # redis.set(uuid,text)
        # 验证码添加有效期这个是300秒
        redis.setex(uuid, 300, text)
        # 4 把验证码的图片返回给前段
        return HttpResponse(image, content_type='image/jpeg')


class Smsview(View):
    def get(self, request, mobile):
        # 验证手机号
        # print(mobile)
        if not mobile:
            return JsonResponse({'code': 300, 'errmsg': '手机号为空'})
        # 正则校验图形验证码
        # - 3 校验图片验证码是否正确
        # /sms_codes/15506373808/?image_code=wnqx&image_code_id=fdd7fe8e-9012-42a3-a535-205df14751ce
        # 用户发过来的图片验证码image_code
        image_code: str = request.GET.get('image_code')
        print('image_code', image_code)
        image_code_uuid = request.GET.get('image_code_id')
        try:
            # 获取保存在redis 里的图片验证码
            redis: Redis = get_redis_connection('code')
            print(redis)
            image_code_redis = redis.get(image_code_uuid)

            if not image_code_redis:
                return JsonResponse({'code': 400, "errmsg": '验证码过期'})
            image_code_redis = image_code_redis.decode()
            print('image_code_redis', image_code_redis)
            if image_code.lower() != image_code_redis.lower():
                return JsonResponse({'code': 500, "errmsg": '验证码错误'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 600, "errmsg": '网络异常'})
        # 4给手机号发送短信 第三方
        print('发送短信给', mobile)
        # 1.根据key:flag_手机号，获取值
        flag_send = redis.get('flag_%s' % mobile)
        # 2如果值存在，返回错误响应，避免频繁的发送
        if flag_send:
            return JsonResponse({'code': 110, "errmsg": '验证码已发送，请稍后再试'})
        # 3如果不存在继续发送短信
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        # SmsUtil().send_message(mobile=mobile, code=sms_code)
        # 异步调用
        send_sms_code.delay(mobile=mobile, code=sms_code)
        # 创建redis的管道pipline对象
        pl = redis.pipeline()
        # 2把redis的请求操作添加到管道
        pl.setex('smscode_%s' % mobile, 60 * 3, sms_code)
        pl.setex('flag_%s' % mobile, 120, 1)
        # 3 执行所以操作
        pl.execute()

        # # 保存到redis数据库keysmscode_18726873989 value sms_code
        # redis.setex('smscode_%s' % mobile, 60 * 3, sms_code)
        # # 4 发送完毕保存key:flag_手机号 value:1 有效期：60（和前段倒计时一样）
        # redis.setex('flag_%s' % mobile, 120, 1)
        # - 5 返回响应02
        return JsonResponse({'code': 0, "errmsg": "ok"})